#-*- coding: utf8 -*-
__author__ = 'baixiaoustc'
import urllib2, urllib
from common import baseweb
import json, sys


KEY = 'bPZSWbtcL3SVqUAD1S4jmOWa'

class codoon_map(baseweb.base_web):

    def __init__(self, origin, destination, region):
        self.mapurl = 'http://api.map.baidu.com/direction/v1'
        self.origin = origin#u'上地五街'
        self.destination = destination#u'北京大学'
        self.region = region#u'北京'
        self.point_list = []

    def do_modify_info(self):
        origin = raw_input(u'起始点: ')
        destination = raw_input(u'结束点: ')
        #region = raw_input(u'在哪儿: ')
        self.origin = origin
        self.destination = destination
        #self.region = region

    def do_get_data(self):
        global KEY
        _orig = urllib.quote(self.origin)#.encode('utf8'))
        _dest = urllib.quote(self.destination)#.encode('utf8'))
        _regi = urllib.quote(self.region)#.encode('utf8'))
        _url = self.mapurl + '?mode=walking&origin=%s&destination=%s&region=%s&output=json&ak=%s'\
            % (_orig, _dest, _regi, KEY)
        #print _url
        mdata = self._get_web_data(_url)
        if '200' != mdata[0]:
            print 'not 200'
            return
        jdata = json.loads(mdata[1])
        print mdata[1]
        return jdata

    def do_parse_data(self, data):
        if data['status'] is not 0:
            print 'status error'
            return
        if data['type'] is 2:
            print 'get precisely map'
            self.do_find_map(data)
            return 0
        elif data['type'] is 1:
            print 'need to choose origin or destination'
            self.do_choose_map(data)
            return -1

    def do_find_map(self, data):
        result = data['result']
        routes = result['routes']
        print 'total %d routes' % len(routes)
        for _route in routes:
            print 'total %d meters' % _route['distance']
            print 'total %d secends' % int(_route['duration'])
            steps = _route['steps']
            print 'total %d steps' % len(steps)
            count = 0
            for _step in steps:
                count += 1
                print '[step %d]' % count
                print 'distance %d, direction %d' % (_step['distance'], _step['direction'])
                print 'OriginLocation (%f, %f)'%(_step['stepOriginLocation']['lat'], _step['stepOriginLocation']['lng'])
                #print _step['stepOriginInstruction']
                print 'DestinationLocation (%f, %f)'%(_step['stepDestinationLocation']['lat'], _step['stepDestinationLocation']['lng'])
                #print _step['stepDestinationInstruction']
                #print _step['type']
                print _step['instructions'].replace('<b>','').replace('</b>','')
                path = _step['path'].split(';')
                for _point in path:
                    x = _point.split(',')[0]
                    y = _point.split(',')[1]
                    #print '(%f, %f)' % (float(x), float(y))
                    self.point_list.append((float(x), float(y)))

    def do_choose_map(self, data):
        result = data['result']
        origin = result['origin']
        destination = result['destination']
        print 'total %d option in origin' % len(origin['content'])
        for _orig in origin['content']:
            print 'name: %s' % _orig['name']
            print 'address: %s' % _orig['address']
        print 'total %d option in destination' % len(destination['content'])
        for _dest in destination['content']:
            print 'name: %s' % _dest['name']
            print 'address: %s' % _dest['address']
        self.do_modify_info()

    def do_main(self):
        count = 0
        while count < 3:
            data = self.do_get_data()
            if self.do_parse_data(data) == 0:
                break
            count += 1
        if count < 3:
            print self.point_list

if __name__ == "__main__":
    reload(sys)
    sys.setdefaultencoding('utf-8')
    mode = raw_input('choose mod: ')
    if mode == '0':
        origin = '清华大学'
        destination = '北京大学'
        region = '北京'
    elif mode == '1':
        origin = '启明花园'
        destination = '软件园'
        region = '成都'
    else:
        origin = raw_input(u'起始点: ')
        destination = raw_input(u'结束点: ')
        region = raw_input(u'在哪儿: ')
    xx = codoon_map(origin, destination, region)
    xx.do_main()